const express = require('express')
const router = express.Router()
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const userDb = require('../db/user-db')
const moment = require('moment')
const crypto = require('crypto')
const { SESClient } = require("@aws-sdk/client-ses");
const { SendEmailCommand } = require("@aws-sdk/client-ses");
const checkType = require('../utils/checkType')

router
    .post('/', async(req, res) => {
        let {body: {maddr}} = req
        logI("A-S", maddr, "send_email_verification_code", `${JSON.stringify(req.body)}`, "null")
        try {
            const error = checkType.sendEmailCode(req.body)
            if (error) {
                retError("send_email_verification_code",  maddr, 10001,  error.details[0].message, res);
            } else {
                let data = await userDb.mailExist(maddr);
                if(data){
                    const sesClient = new SESClient({
                        region: process.env.AWS_REGION, // 显式指定区域（覆盖默认）
                        credentials: {  // 若需手动指定密钥
                            accessKeyId: process.env.AWS_ACCESSKEYID,
                            secretAccessKey: process.env.AWS_SECRETACCESSKEY
                        }
                    });
                    const code = crypto.randomInt(0, 1000000).toString().padStart(6, '0');
                    const params = {
                        Source: process.env.AWS_SENDER_EMAIL, // 已验证的邮箱
                        Destination: {
                            ToAddresses: [maddr], // 收件人列表
                        },
                        Message: {
                            Subject: { Data: "HSE WISE Verification Code to Reset Password" },
                            Body: {
                                Html: {
                                    Data: '<p>You have selected this email address as your HSE WISE account. To verify that this email address belongs to you, please enter the following verification code on the email verification page:</p><br>' +
                                        '<h3>' + code + '</h3><br>' +
                                        '<p>The verification code will expire five minutes after this email is sent.</p>' +
                                        '<p>If you did not make this request, you can ignore this email. A HSE WISE Blue account can only be created after verification.</p><br>'// html body
                                }
                            },
                        },
                    };
                    const createTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    await userDb.updateCode(code,createTime,maddr);
                    const command = new SendEmailCommand(params);
                    sesClient.send(command)
                        .then(data => {
                            retSuccess("send_email_verification_code",  maddr, 0, "", res);
                        })
                        .catch(err => {
                            retError("send_email_verification_code",  maddr, 10005, err, res);
                        })
                }else{
                    retError("send_email_verification_code",  maddr, 10007, "user does not exist", res);
                }
            }
        } catch (e) {
            retError("send_email_verification_code",  maddr, 10001, e, res);
        }
    })

module.exports = router
